package com.adcc.ags.msgStore.service;

import com.adcc.ags.msgStore.common.Constant;
import com.adcc.ags.msgStore.dao.MsgStoreDao;
import com.adcc.ags.msgStore.dao.MsgStoreDaoImpl;
import com.adcc.ags.msgStore.entity.file.FileErrorCode;
import com.adcc.ags.msgStore.managed.MessageForward;
import com.adcc.utility.log.Log;
import com.adcc.utility.mq.entity.Message;

/**
 * Created by ZHANG on 2017/3/1.
 */
public class MsgStoreInFileServiceImpl extends MsgStoreInFileService {

    private MsgStoreDao msgStoreDao = MsgStoreDaoImpl.getInstance();

    /**
     * 保存报文到oracle数据库中
     * @param message
     */
    @Override
    public FileErrorCode saveMessageToFile(Message message) {
        if(message !=null){
            return msgStoreDao.saveFile(message.getContent(), MessageForward.getInstance().getPath(),
                    String.valueOf(message.getHead().get(Constant.TRAFFIC_MESSAGE_MSG_ID)));
        }else{
            return FileErrorCode.SAVE_ERROR;
        }
    }

    @Override
    public void onReceive(Object message) throws Exception {
        if(message == null){
            Log.error(MsgStoreInFileServiceImpl.class.getName(), "receive message is null");
            unhandled(message);
        }else{
            if(message instanceof Message){
                Message msg = (Message)message;
                FileErrorCode flag = saveMessageToFile(msg);
                if (flag == FileErrorCode.SAVE_ERROR) {
                    Log.error(MsgStoreInFileServiceImpl.class.getName(), "store message in file error!\r\n"+msg.toString());
                } else if(flag == FileErrorCode.PATH_ERROR) {
                    Log.error(MsgStoreInFileServiceImpl.class.getName(), "file path is null!\r\n"+msg.toString());
                } else if(flag == FileErrorCode.CLOSE_ERROR) {
                    Log.error(MsgStoreInFileServiceImpl.class.getName(), "Close BufferedOutputStream object error!");
                }
            }
        }
    }
}
